package com.ntd.util.img;

import cn.hutool.core.util.StrUtil;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.imaging.png.PngMetadataReader;
import com.drew.imaging.png.PngProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import ntd.util.UtilLog;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 照片处理工具
 *
 * @author liuwenju
 * @date 2021/09/24
 */
public class UtilPhoto {

    public static void main(String[] args) throws JpegProcessingException, IOException, PngProcessingException {
        Map<String, String> stringStringMap = picAnalysis("C:\\Users\\Administrator\\Desktop\\jpg2.jpg");
        UtilLog.info(stringStringMap);
    }

    public static Map<String, String> picAnalysis(String path) {
        return transformMap(readMetadata(path));
    }

    private static Map<String, String> transformMap(Metadata metadata) {
        Map<String, String> map = new HashMap();
        Iterator<Directory> it = metadata.getDirectories().iterator();
        while (it.hasNext()) {
            Directory exif = it.next();
            Iterator<Tag> tags = exif.getTags().iterator();
            while (tags.hasNext()) {
                Tag tag = tags.next();
                map.put(tag.getTagName(), tag.getDescription());
                UtilLog.info(tag.toString());
            }
        }
        return map;
    }

    private static Metadata readMetadata(String path) {
        try {
            File picFile = new File(path);
            if (StrUtil.endWithIgnoreCase(path, "jpeg") || StrUtil.endWithIgnoreCase(path, "jpg")) {
                return JpegMetadataReader.readMetadata(picFile);
            } else if (StrUtil.endWithIgnoreCase(path, "png")) {
                return PngMetadataReader.readMetadata(picFile);
            }
        } catch (JpegProcessingException | PngProcessingException e) {
            throw new IllegalAccessError("文件解析失败");
        } catch (IOException e) {
            throw new IllegalAccessError("文件读取失败");
        }
        throw new IllegalAccessError("不支持当前文件类型");
    }
}
